package com.distribution.system.utils.zop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.distribution.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: GodLu
 * @create: 2024-05-06 16:37
 * @description: TODO
 */
@Slf4j
public class ZopUtil {
    private static final String operatorUrl = "http://cd.10010.com/zop/link/king/card/diffnet/check";
    private static final String APP_CODE = "B89CB06E3741410AB27F00D7E5F78901";
    private static final String HMAC = "8duXF0HH+xO8v/2tQm/Q20IYk/B5LmgFreEY98eiiBdWgLJ+vGZ9P/dDrveNpvBNBwtl0MO+SiYgLoFiAFw1MQ==";
    private static final String AES = "gJ4Fc13zcVfYVVdDVl8nyA==";

    public static boolean isDifferentNet(Map<String,String> paramsMap) throws Exception {
        JSONObject baseReq = new JSONObject();
        baseReq.put("appCode",APP_CODE);
        ReqObj<Map<String,Object>> obj = new ReqObj<Map<String,Object>>();
        ReqHeadBean head = new ReqHeadBean();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        head.setTimestamp(formatter.format(new Date()));
        head.setUuid(String.valueOf(UUID.randomUUID()));
        head.setSign(makeSign(head));
        obj.setHead(head);

        Map<String,Object> body = new HashMap<>();
        //以下就是接口调用的业务入参，各个接口均按照各自规范入参字段填写；如消息接口：
        body.put("channel",paramsMap.get("channel"));
        body.put("certId",paramsMap.get("certId"));
        body.put("certName",paramsMap.get("certName"));
        body.put("provinceCode",paramsMap.get("provinceCode"));
        body.put("cityCode",paramsMap.get("cityCode"));
        obj.setBody(body);
        log.info("异网校验请求参数：" + obj.toString());
        //reqObj节点需要加密时
        baseReq.put("reqObj", SecurityTool.encrypt(AES, JSON.toJSONString(obj)));

        //log.info("请求报文："+ JSON.toJSONString(baseReq));
        MediaType json  = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .build();
        RequestBody requestBody = RequestBody.create(json, JSON.toJSONString(baseReq));
        Request request = new Request.Builder()
                .url(operatorUrl)
                .post(requestBody)
                .build();
        Response response = client.newCall(request).execute();
        if (response.body() == null){
            log.error("异网请求失败，响应体为空");
            throw new ServiceException("异网请求失败，响应体为空");
        }
        String resStr = response.body().string();
        log.info("异网校验返回报文："+ resStr);
        JSONObject responseJsonObj = JSON.parseObject(resStr);
        //各个接口对于成功和失败，以及返回数据解析的逻辑不尽相同，严格按照各自规范建议处理：
        if ("0000".equals(responseJsonObj.getString("rspCode"))){
            //成功
            JSONObject bodyJsonObj = responseJsonObj.getJSONObject("body");
            String orderDifferentNet = bodyJsonObj.getString("orderDifferentNet");
            String biOrderDifferentNet = bodyJsonObj.getString("biOrderDifferentNet");
            // 优先应用自然人判断，自然人判断返回为空或者未获取，再应用经分判断，经分接口每月1号至10号左右不会返回数据。
            if (orderDifferentNet == null || "2".equals(orderDifferentNet)){
                return "2".equals(biOrderDifferentNet);
            }else {
                return !"1".equals(orderDifferentNet);
            }
        }else{
            //失败
            return false;
        }
    }

    private static String makeSign (ReqHeadBean req) throws Exception {
        //appCode+head节点（除sign节点,字母升序）+hmac密钥
        String sb = "appCode" + APP_CODE +
                "timestamp" + req.getTimestamp() +
                "uuid" + req.getUuid() +
                HMAC;
        return SecurityTool.sign(HMAC, sb);
    }
}
